package com.mab.mall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.mab.mall.cart.feign.ProductFeignService;
import com.mab.mall.cart.interceptor.AuthInterceptor;
import com.mab.mall.cart.service.ICartService;
import com.mab.mall.cart.vo.Cart;
import com.mab.mall.cart.vo.CartItem;
import com.mab.mall.cart.vo.SkuInfoVo;
import com.msb.common.constant.CartConstant;
import com.msb.common.utils.R;
import com.msb.common.vo.MemberVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements ICartService {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    /**
     * 查询当前登录用户的所有购物车数据
     * @return
     */
    @Override
    public Cart getCarList() {
        BoundHashOperations<String, Object, Object> cartKey = getCartKey();
        Set<Object> keys = cartKey.keys();
        Cart cart = new Cart();
        List<CartItem> list = new ArrayList<>();
        if (keys != null) {
            for (Object k :keys) {
                String key = (String) k;
                Object o = cartKey.get(key);
                String json = (String) o;
                CartItem  item = JSON.parseObject(json,CartItem.class);
                list.add(item);
            }
        }
        cart.setItems(list);
        return cart;
    }

    /**
     * 把商品加入购物车
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public CartItem addCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartKey = getCartKey();
        Object o = cartKey.get(num);
        //如果redis存储在商品中的信息，只需要修改商品数量
        if (o != null){
            String json = (String) o;
            CartItem  item = JSON.parseObject(json,CartItem.class);
            item.setCount(num);
            cartKey.put(skuId,JSON.toJSONString(item));
            return item;
        }
        CartItem item = new CartItem();
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(()->{
            //远程调用获取商品信息
            R info = productFeignService.info(skuId);
            if(info.getCode() == 0){
                String skuInfoJson = (String) info.get("skuInfoJson");
                SkuInfoVo skuInfo = JSON.parseObject(skuInfoJson,SkuInfoVo.class);
                item.setCount(num);
                item.setImage(skuInfo.getSkuDefaultImg());
                item.setPrice(skuInfo.getPrice());
                item.setSkuId(skuId);
                item.setTitle(skuInfo.getSkuTitle());
                item.setSpuId(skuInfo.getSpuId());
            }
        },threadPoolExecutor);
        CompletableFuture<Void> future2 = CompletableFuture.runAsync(()->{
            //获取商品销售属性
            List<String> saleAttrs = productFeignService.getSkuSaleAttrs(skuId);
            item.setSkuAttr(saleAttrs);
        },threadPoolExecutor);

        CompletableFuture.allOf(future1,future2).get();
        //把数据存储到Redis中
        String jsonString = JSON.toJSONString(item);
        cartKey.put(skuId,jsonString);
        return item;
    }

    /**
     * 获取当前登录用户信息用户选中的商品信息，购物车中
     * @return
     */
    @Override
    public List<CartItem> getUserCarItems() {
        BoundHashOperations<String, Object, Object> cartKey = getCartKey();
        List<Object> values = cartKey.values();
        List<CartItem> collect = null;
        if (values != null) {
            collect = values.stream().map(item -> {
                String json = (String) item;
                return JSON.parseObject(json, CartItem.class);
            }).filter(CartItem::isCheck).collect(Collectors.toList());
        }
        return collect;
    }

    private BoundHashOperations<String, Object, Object> getCartKey() {
        MemberVO memberVO = AuthInterceptor.threadLocal.get();
        String cartKey = CartConstant.CART_PREFIX+memberVO.getId();
        return redisTemplate.boundHashOps(cartKey);
    }
}
